from sqlalchemy import Column, Integer, String, Sequence, DateTime
from sqlalchemy.orm import Session

from app.db import db_query, db_update, Base


class Archive(Base):
    """
    画师表
    """
    # ID
    id = Column(Integer, Sequence('id'), primary_key=True, index=True)
    # 漫画ID
    comic_id = Column(Integer)
    # 标题
    title = Column(String)
    # 标题(显示)
    title_display = Column(String)
    # 缩略图
    thumb = Column(String)
    # 上传时间
    upload_time = Column(String)
    # 上传人
    upload_by = Column(String)
    # 文件名
    file_name = Column(String)
    # 文件路径
    file_path = Column(String)
    # 档案解压路径
    unpack_path = Column(String)
    # 文件大小
    file_size = Column(Integer)
    # 源地址url
    url = Column(Integer)
    # 总页数
    pages = Column(Integer)
    # 阅读进度
    progress = Column(Integer)
    # 文件md5
    md5 = Column(String)
    # 添加时间
    add_time = Column(DateTime)
    # 上次阅读时间
    last_read_time = Column(DateTime)
    # 是否新书
    is_new = Column(Integer)
    # 分类ID
    categories_id = Column(Integer)
    # 标签ID列表
    tags_id = Column(String)

    @staticmethod
    @db_query
    def get_by_title(db: Session, title: String):
        return db.query(Archive).filter(Archive.title.__eq__(title)).first()

    @db_update
    def delete_by_title(self, db: Session, title: String):
        archive = self.get_by_title(db, title)
        if archive:
            archive.delete(db, archive.id)
        return True

    @staticmethod
    @db_query
    def list_by_page(db: Session, page: int = 1, count: int = 30):
        result = db.query(Archive).order_by(Archive.last_read_time.desc()).offset((page - 1) * count).limit(
            count).all()
        result.sort(key=lambda x: x.reg_time, reverse=False)
        return list(result)
